package com.cc.service

import com.cc.common.model.Query
import com.cc.mapper.CategoryMapper
import com.cc.mapper.ScriptMapper
import com.cc.model.Category
import com.cc.model.Repository
import com.cc.model.convert.CategoryConvert
import com.cc.model.convert.ScriptConvert
import com.cc.model.dto.CategoryDto
import com.cc.model.dto.ScriptDto
import com.mybatisflex.core.paginate.Page
import com.mybatisflex.core.query.QueryWrapper
import com.mybatisflex.kotlin.extensions.db.paginate
import com.mybatisflex.kotlin.extensions.kproperty.like
import com.mybatisflex.spring.service.impl.ServiceImpl
import org.springframework.stereotype.Service
import java.time.LocalDateTime

/**
 * CategoryService
 * @author aa
 * @since 2024/4/25
 * @version 1.0
 */
@Service
class CategoryService(
    private val categoryConvert: CategoryConvert,
    private val scriptMapper: ScriptMapper,
    private val scriptConvert: ScriptConvert,
) : ServiceImpl<CategoryMapper, Category>() {

    fun create(category: CategoryDto): Boolean = categoryConvert.toEntity(category).apply {
        addTime = LocalDateTime.now()
    }.run {
        return save()
    }

    fun findCategoryListByPage(query: Query<CategoryDto?>): Page<CategoryDto> {
        return paginate(Page.of<Category>(query.page, query.limit)) {
            query.p?.let { a ->
                where {
                    Category::categoryName like a.categoryName!!
                }.orderBy(Repository::editTime, false)
            }
        }.map {
            categoryConvert.toDto(it)
        }
    }

    fun findListByPageSimple(cid: String, name: String, pageNum: Int, pageSize: Int, type: Int?): Page<ScriptDto> {
        val queryWrapper = QueryWrapper()
        queryWrapper.eq("CATEGORY_ID", cid)
        queryWrapper.like("SCRIPT_NAME", name)
        if (type != null) {
            queryWrapper.eq("SCRIPT_TYPE", type)
        }
        val list: Page<ScriptDto> = scriptMapper.paginate(Page(pageNum, pageSize), queryWrapper).map {
            scriptConvert.toDto(it)
        }
        return list
    }


}